<template>
  <view class="header-box">
    <view v-if="maintenanceMyList == null">
      <view class="warring_top">
 <!--       <image src="https://mkservice.mk-iot.com/subFile/mkApplet/warringico.png" class="warringico"></image> -->
        <view class="warring_text">
          抱歉，您并未发布任何报修
        </view>
        <view class="goToSendText" @tap="goToPubish">
          前往去发布
        </view>
      </view>
      <button class="warring_btn" @tap="escUp">确定</button>
    </view>
    <view v-else>
      <block v-for="(item,index) in maintenanceMyList" :key="index">
        <!--组件-报修列表-->
        <maintenance_list :mainteanceList="item"></maintenance_list>
      </block>
      <!--底部-->
      <myBottom :mybottom="maintenanceMyList"></myBottom>
    </view>
    <view>
      <!-- 输入框示例 -->
      <uni-popup ref="popup" background-color="#fff" :show='show' @change="popupchange">
        <view class="popup-content">
          <uni-table ref="table" :loading="loading" border stripe emptyText="暂无更多数据"
            @selection-change="selectionChange">
            <uni-tr>
              <uni-th width="80" align="center">昵称</uni-th>
              <uni-th align="center">手机号</uni-th>
              <uni-th width="100" align="center">操作</uni-th>
            </uni-tr>
            <uni-tr v-for="(item, index) in userList" :key="index">
              <uni-td align="center">
                <view class="name">{{ item.nickName }}</view>
              </uni-td>
              <uni-td align="center">{{ item.phonenumber }}</uni-td>
              <uni-td align="center">
                <view class="uni-group">
                  <button class="uni-button" size="mini" type="primary" @tap="clickUser(item.userId,item.nickName,item.phonenumber)">选择</button>
                </view>
              </uni-td>
            </uni-tr>
          </uni-table>
          <view class="uni-pagination-box"><uni-pagination show-icon :page-size="userqueryParams.pageSize"
              :current="userqueryParams.pageCurrent" :total="userTotal" @change="change" /></view>
        </view>
        <view class="btn_item">
          <button class="cancal" type="warn" @tap="close" size="mini">关闭</button>
        </view>
      </uni-popup>
      <!-- 输入框示例 -->
      <uni-popup ref="inputDialog" type="dialog">
        <uni-popup-dialog v-if="isDialog" ref="inputClose" mode="input" title="拒绝理由" placeholder="请输入拒绝理由"
          @confirm="dialogInputConfirm">
          <view>
          <uni-easyinput type="text"
                       v-model="descs"
                       :placeholder="placeholder"/>
                 </view>
                 </uni-popup-dialog>
      </uni-popup>
    </view>
  </view>
</template>

<script>
  import {
    queryStateToList,
    addTaskState,
    updateTask,
    sendScheduleMessage,
    delRepairImgByCode,
    queryByrepairImgCodelist,
    sendMessage
  } from "@/api/system/task/task.js"
  import getDateTime from '../../utils/getdateTime.js'
  import myBottom from '../components/my-bottom/my-bottom.vue';
  import maintenance_list from '../components/maintenance-list/maintenance-list.vue';
  import {
    getUserItme,selectByRepairman
  } from "@/api/system/user"
  export default {
    components: {
      myBottom,
      maintenance_list
    },
    data() {
      return {
        //显示弹出框
        isDialog: false,
        // 是否正在请求数据,节流阀
        isloading: false,
        descs:"",
        count: 0,
        queryParams: {
          pageNum: 1,
          pageSize: 6,
          warrantyPersonId: '',
          maintenanceStatus: '',
        },
        maintenanceCode: null,
        maintainerId: null,
        warrantyPersonId: null,
        distributionType:null,
        urgency:null,
        loading: false,
        maintenanceMyList: [],
        userList: [],
        userqueryParams: {
          pageNum: 1,
          pageSize: 5
        },
        stateData: {
          maintenanceCode: null,
          state: "",
          datetime: getDateTime.dateTimeStr('y-m-d h:i:s'),
          descs: ""
        },
        // 用户数据总量
        userTotal: 0,
      }
    },
    //页面创建时调用数据刷新
    created() {
      uni.$on("toOverList", (data) => {
        this.maintenanceMyList = []
        this.queryParams.pageNum = data.value
        this.queryMyToList()
      });
    },
    onLoad(option) {
      this.queryParams.warrantyPersonId = option.userid
      this.queryMyToList()
    },
    methods: {
      toBack() {
        uni.navigateBack()
      },
      queryMyToList(cb) {
        // 打开遮罩层
        this.$modal.loading("数据加载中...");
        // ** 打开节流阀
        this.isloading = true
        queryStateToList(this.queryParams).then(response => {
          if (response.code === 200) {
            // 关闭遮罩层
            this.$modal.closeLoading();
            uni.stopPullDownRefresh()
            // 关闭节流阀
            this.isloading = false
            // 只要数据请求完毕，就立即按需调用 cb 回调函数
            cb && cb()
            this.maintenanceMyList = [...this.maintenanceMyList, ...response.rows]
            this.count = response.total
          }
        })
      },
      //去新增报修页
      goToPubish() {
        this.$tab.navigateTo('/subpkg/maintenance/maintenance_edit')
      },
      //确定跳转首页
      escUp() {
        this.$tab.reLaunch('/subpkg/index/index')
      },
      //弹窗时出现滑动穿透解决方案
      popupchange(e) {
        this.show = e.show
      },
  /**查询用户列表 */
      getuserList() {
        this.loading = true;
        selectByRepairman(this.userqueryParams).then(response => {
          this.userList = response.rows;
          this.loading = false;
        });
      },
      // 分页触发
      change(e) {
        this.userqueryParams.pageNum = e.current
        this.getuserList()
      },
      //选择派发人员取消
      close() {
        // TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
        this.$refs.popup.close()
      },
      clickUser(userid,nickName,phonenumber) {
        if (this.maintenanceCode !== null && userid !== null) {
          this.$modal.confirm('确定派发该用户去维修吗？').then(() => {
            this.stateData.maintenanceCode = this.maintenanceCode
            this.stateData.state = this.distributionType==1?"维修中":'已重新派单，维修中'
            addTaskState(this.stateData).then(response => {
              if (response.code == 200) {
                const data = {
                  maintenanceCode: this.maintenanceCode,
                  maintenanceStatus: 1,
                  warrantyPersonId:this.warrantyPersonId,
                  maintainerId: userid,
                  startTime: getDateTime.dateTimeStr('y-m-d h:i:s')
                }
                updateTask(data).then(response => {
                  if (response.code === 200) {
                    getUserItme(userid).then(response => {
                      if (response.code == 200 && response.data.openId !=
                        null) {
                        //新增成功调用接口
                        const messagedata = {
                          openid: response.data.openId,
                          selfPage: '/pages/login',
                          maintenanceCode: this.maintenanceCode,
                          urgency: this.urgency == 0 ? '普通维修' : '紧急维修',
                          username: nickName,
                          phonenumber: phonenumber,
                          description: this.urgency == 0 ? '您有一份普通维修单,请在7天内及时处理' : '您有一份紧急维修单,请在3天内及时处理'
                        }
                        sendMessage(messagedata).then(response => {
                          //重置关键数据
                          //操作成功跳转到当前处理中
                         this.empty()
                         this.queryMyToList()
                          if (response.errcode == 0) {
                             this.$modal.msgSuccess("派发成功！")
                             this.$refs.popup.close()
                          } else {
                             this.$modal.msgError("订阅失败");
                             this.$refs.popup.close()
                          }
                        })
                      } else {
                        this.empty()
                        this.queryMyToList()
                        this.$modal.msgSuccess("派发成功！")
                        this.$refs.popup.close()
                      }
                    })
                  }
                })
              }
            })
          })
        }
      },
      dialogInputConfirm(val) {
        const statedata = {
          maintenanceCode: this.maintenanceCode,
          state: "用户已拒绝",
          datetime: getDateTime.dateTimeStr('y-m-d h:i:s'),
          descs: "拒绝原因: " + this.descs
        }
        const data = {
          maintenanceCode: this.maintenanceCode,
          maintenanceStatus: 3,
          repairDescription: ""
        }
        addTaskState(statedata).then(response => {
          if (response.code === 200) {
            updateTask(data).then(response => {
              if (response.code === 200) {
                queryByrepairImgCodelist(this.maintenanceCode).then(response => {
                  if (response.code == 200 && response.data.length > 0) {
                    delRepairImgByCode(this.maintenanceCode).then(response => {
                      if (response.code == 200) {
                        this.sharemethod()
                      }
                    })
                  } else {
                    this.sharemethod()
                  }
                })
              }
            })
          }
        });
      },
      //共用方法
      sharemethod() {
        getUserItme(this.maintainerId).then(response => {
          if (response.code == 200 && response.data.openId != null) {
            //新增成功调用接口
            const messagedata = {
              openid: response.data.openId,
              selfPage: '/pages/login',
              maintenanceCode: this.maintenanceCode,
              maintenanceStatus: "用户已拒绝",
              description: "用户已拒绝,请尽快去查看原因",
            }
            sendScheduleMessage(messagedata).then(response => {
              // 关闭窗口后，恢复默认内容
              this.empty()
              this.queryMyToList()
              this.$refs.inputDialog.close()
              if (response.errcode == 0) {
                this.$modal.msgSuccess("操作成功")
              } else {
                this.$modal.msgError("订阅失败");
              }
            })
          } else {
            this.empty()
            this.queryMyToList()
            this.$refs.inputDialog.close()
            this.$modal.msgSuccess("操作成功")
          }
        })
      },
      empty() {
        //重置关键数据
        this.count = 0
        this.isloading = false
        this.maintenanceMyList = []
        this.queryParams.pageNum = 1
      },
    },
    // 触底的事件
    onReachBottom() {
      // 判断是否还有下一页数据
      if (this.queryParams.pageNum * this.queryParams.pageSize >= this.count) return uni.$showMsg('数据加载完毕')
      // 判断是否正在请求其它数据，如果是，则不发起额外的请求
      if (this.isloading) return
      //让页码值自增+1
      this.queryParams.pageNum += 1
      // 重新获取列表数据
      this.queryMyToList()

    },
    //下拉事件
    onPullDownRefresh() {
      //重置关键数据
      this.empty()
      //重新发起数据请求
      this.queryMyToList()
    },
    //点击返回上一页时传参
    onUnload() {
      uni.$emit("toIndex", {
        value: 1
      });
      // uni.navigateBack({ // 返回上一页
      //   delta: 1
      // });
      // 移除监听事件
      uni.$off("toOverList");
    }
  }
</script>

<style lang="scss">
  .header-box {
    position: sticky;
    top: 0;
    z-index: 2000;

    .warring_top {
      width: 100%;
      padding: 30rpx;
      background-color: #fff;

      .warringico {
        width: 120rpx;
        height: 120rpx;
        margin: 0px auto;
        display: block;
      }

      .warring_text {
        margin: 20px auto;
        text-align: center;
      }

      .goToSendText {
        text-align: center;
        font-size: 25rpx;
        color: #0d91dd;
        font-weight: bold;
      }
    }

    .warring_btn {
      width: 90%;
      background: linear-gradient(to right, #6496F7, #2F6BE3);
      color: #fff;
      margin-top: 50rpx;
    }
    
    .btn_item {
      display: flex;
      margin: 20rpx 0;
    }
  }
</style>